﻿using Application.Common.Interfaces;
using AutoMapper;
using Common.Attributes;
using Common.Services;
using Domain.Entities.Identity;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Common.Enums;

namespace Application.Features.Users.Commands.Update;

/// <summary>
/// 修改用户基本信息
/// </summary>
[Map(typeof(User))]
[Description("修改基本信息")]
[GroupDescription(("用户管理"))]
public class UpdateUserCommand : IRequest<bool>
{
    /// <summary>
    /// 唯一标识
    /// </summary>
    [Required(ErrorMessage = "唯一标识必填的")]
    public long UserId { get; set; }

    /// <summary>
    /// 昵称
    /// </summary>
    [Description("昵称")]
    public string? Nickname { get; set; }

    /// <summary>
    /// 真实姓名
    /// </summary>
    [Description("真实姓名")]
    public string? Realname { get; set; }

    /// <summary>
    /// 手机号码
    /// </summary>
    public string? PhoneNumber { get; set; }

    /// <summary>
    /// 邮箱
    /// </summary>
    public string? Email { get; set; }

    /// <summary>
    /// 性别
    /// </summary>
    [Description("性别")]
    public GenderType GenderType { get; set; }

    /// <summary>
    /// 个性签名
    /// </summary>
    [Description("个性签名")]
    public string? Signature { get; set; }

    /// <summary>
    /// 组织机构唯一标识
    /// </summary>
    public long? OrganizationId { get; set; }

    /// <summary>
    /// 并发标记
    /// </summary>
    [Required(ErrorMessage = "并发标记必填的")]
    public string ConcurrencyStamp { get; set; }
}

/// <summary>
/// 处理程序
/// </summary>
public class UpdateUserCommandHandler : IRequestHandler<UpdateUserCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public UpdateUserCommandHandler(
        IApplicationDbContext context,
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(UpdateUserCommand request, CancellationToken cancellationToken)
    {
        var user = await _context.Users
            .SingleOrDefaultAsync(x => x.Id == request.UserId && x.ConcurrencyStamp == request.ConcurrencyStamp, cancellationToken);

        _mapper.Map(request, user);
        _context.Users.Update(user!);

        return true;
    }
}